package me.zhengjie.tools.rest

import me.zhengjie.common.utils.*
import me.zhengjie.logging.annotation.Log

import me.zhengjie.tools.service.dto.PictureQueryCriteria
import me.zhengjie.tools.service.PictureService

import io.swagger.v3.oas.annotations.media.Schema
import jakarta.servlet.http.HttpServletResponse
import org.springframework.data .domain.Pageable
import org.springframework.http.HttpStatus
import org.springframework.http.ResponseEntity
import org.springframework.security.access.prepost.PreAuthorize
import org.springframework.web.bind.annotation .*
import org.springframework.web.multipart.MultipartFile
import java.io.IOException
/**
 * @author 郑杰
 * @date 2018/09/20 14:13:32
 */
@RestController
@RequestMapping("/api/pictures")
@Schema(description = "工具：免费图床管理")
class PictureController(private val pictureService: PictureService) {
    @Log("查询图片")
    @PreAuthorize("@el.check('pictures:list')")
    @GetMapping
    @Schema(description = "查询图片")
    fun getRoles(criteria: PictureQueryCriteria, pageable: Pageable?): ResponseEntity<*> {
        return ResponseEntity(pictureService.queryAll(criteria, pageable), HttpStatus.OK)
    }

    @Log("导出数据")
    @Schema(description = "导出数据")
    @GetMapping(value = ["/download"])
    @PreAuthorize("@el.check('pictures:list')")
    @Throws(
        IOException::class
    )
    fun download(response: HttpServletResponse?, criteria: PictureQueryCriteria) {
        pictureService.download(pictureService.queryAll(criteria), response)
    }

    @Log("上传图片")
    @PreAuthorize("@el.check('pictures:add')")
    @PostMapping
    @Schema(description = "上传图片")
    fun upload(@RequestParam file: MultipartFile): ResponseEntity<*> {
        val userName = SecurityUtils.username
        val picture = pictureService.upload(file, userName)
        val map: MutableMap<String, Any> = HashMap(3)
        map["errno"] = 0
        map["id"] = picture!!.id!!
        map["data"] = arrayOf(picture.url)
        return ResponseEntity<Map<String, Any>>(map, HttpStatus.OK)
    }

    @Log("删除图片")
    @Schema(description = "删除图片")
    @PreAuthorize("@el.check('pictures:del')")
    @DeleteMapping(value = ["/{id}"])
    fun delete(@PathVariable id: Long): ResponseEntity<*> {
        pictureService.delete(pictureService.findById(id))
        return ResponseEntity<Any?>(HttpStatus.OK)
    }

    @Log("多选删除图片")
    @Schema(description = "多选删除图片")
    @PreAuthorize("@el.check('pictures:del')")
    @DeleteMapping
    fun deleteAll(@RequestBody ids: Array<Long>): ResponseEntity<*> {
        pictureService.deleteAll(ids)
        return ResponseEntity<Any?>(HttpStatus.OK)
    }
}